package middleware

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"time"
)

type bodyLogWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}
func (w bodyLogWriter) WriteString(s string) (int, error) {
	w.body.WriteString(s)
	return w.ResponseWriter.WriteString(s)
}

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		bodyLogWriter := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
		c.Writer = bodyLogWriter

		//开始时间
		startTime := time.Now().UnixNano()

		//处理请求
		c.Next()

		//结束时间
		endTime := time.Now().UnixNano()

		var resp = make(map[string]interface{})
		_ = json.Unmarshal([]byte(bodyLogWriter.body.String()), &resp)

		//日志格式
		accessLogMap := make(map[string]interface{})

		accessLogMap["time"] = startTime
		accessLogMap["method"] = c.Request.Method
		accessLogMap["uri"] = c.Request.RequestURI
		accessLogMap["proto"] = c.Request.Proto
		accessLogMap["ua"] = c.Request.UserAgent()
		accessLogMap["referer"] = c.Request.Referer()
		accessLogMap["post_data"] = c.Request.PostForm.Encode()
		accessLogMap["header"] = c.Request.Header
		accessLogMap["client_ip"] = c.ClientIP()
		accessLogMap["respond"] = resp
		accessLogMap["cost_time"] = fmt.Sprintf("%vms", (endTime-startTime)/1e6)

		accessLogJson, _ := json.Marshal(accessLogMap)
		logFileName := time.Now().Format("20060102")

		if f, err := os.OpenFile(fmt.Sprintf("runtime/log/%s.log", logFileName), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666); err != nil {
			log.Println(err)
		} else {
			_, _ = f.WriteString(string(accessLogJson) + "\n")
		}
	}
}
